//
//  WBComoseTypeView.swift
//  weibo
//
//  Created by wenquan wang on 1/31/17.
//  Copyright © 2017 wenquan wang. All rights reserved.
//

import UIKit
import pop

class WBComposeTypeView: UIView {

    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var closeButtonCenterXCons: NSLayoutConstraint!
    
    @IBOutlet weak var returnButtonCenterXCons: NSLayoutConstraint!
    
    @IBOutlet weak var returnButton: UIButton!
    
    let buttonsInfo = [
        ["imageName": "tabbar_compose_idea", "title": "text", "clsName": "WBComposeViewController"],
        ["imageName": "tabbar_compose_photo", "title": "Photo"],
        ["imageName": "tabbar_compose_weibo", "title": "weibo"],
        ["imageName": "tabbar_compose_lbs", "title": "check in"],
        ["imageName": "tabbar_compose_review", "title": "review"],
        ["imageName": "tabbar_compose_more", "title": "more", "actionName": "clickMore"],
        ["imageName": "tabbar_compose_friend", "title": "friend"],
        ["imageName": "tabbar_compose_wbcamera", "title": "wbcamera"],
        ["imageName": "tabbar_compose_music", "title": "music"],
        ["imageName": "tabbar_compose_shooting", "title": "take photo"]
    ]
    private var completionBlock: ((String?)->())?
    // MARK: instance method
    class func composeTypeView() -> WBComposeTypeView {
        let nib = UINib(nibName: "WBComposeTypeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBComposeTypeView
        v.frame = UIScreen.main.bounds
        v.setupUI()
        return v
    }

    func show(completion: @escaping((clsName: String?))->()) {
        completionBlock = completion
        
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        vc.view.addSubview(self)
        //animate
        showCurrentView()
    }
    
    // MARK: -- event
    @objc func clickButton(selectedButton: WBComposeTypeButton){
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        for (i, btn) in v.subviews.enumerated() {
            let scaleAnim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            let scale = (selectedButton == btn) ? 2 : 0.2
            let value = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnim.toValue = value
            scaleAnim.duration = 0.5
            
            btn.pop_add(scaleAnim, forKey: nil)
            
            let alphaAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnim.toValue = 0.2
            alphaAnim.duration = 0.5
            
            btn.pop_add(alphaAnim, forKey: nil)
            
            if( i == 0)
            {
                alphaAnim.completionBlock = { (_, _) in
                    print("finished anim....")
                    self.completionBlock?(selectedButton.clsName)
                }
            }
        }
    }
    @objc func clickMore(){
        scrollView.setContentOffset(CGPoint(x: scrollView.bounds.width, y: 0), animated: true)
        returnButton.isHidden = false
        let margin = scrollView.bounds.width / 6
        closeButtonCenterXCons.constant += margin
        returnButtonCenterXCons.constant -= margin
        UIView.animate(withDuration: 0.25) { 
            self.layoutIfNeeded()
        }
    }
    
    @IBAction func clickReturn(_ sender: Any) {
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        
        closeButtonCenterXCons.constant = 0
        returnButtonCenterXCons.constant = 0
        
        UIView.animate(withDuration: 0.25, animations: { 
            self.layoutIfNeeded()
            self.returnButton.alpha = 0
        }) { (_) in
            self.returnButton.isHidden = true
            self.returnButton.alpha = 1
        }
    }
    
    
    @IBAction func close(_ sender: Any) {
        hideButtons()
        //removeFromSuperview()
        
    }
}

extension WBComposeTypeView {
    func hideButtons(){
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        for (i, btn) in v.subviews.enumerated().reversed() {
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + 400
            
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i)*0.025
            
            btn.layer.pop_add(anim, forKey: nil)
            
            if i == 0 {
                anim.completionBlock = { (_, _) in
                    self.hidCurrentView()
                }
            }
        }
        
    }
    private func hidCurrentView(){
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.fromValue = 1
        anim.toValue = 0
        anim.duration = 0.25
        pop_add(anim, forKey: nil)
        anim.completionBlock = { (_, _) in
            self.removeFromSuperview()
        }
    }
    func showCurrentView(){
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        anim.fromValue = 0
        anim.toValue = 1
        anim.duration = 0.25
        
        pop_add(anim, forKey: nil)
        
        showButtons()
    }
    private func showButtons(){
        let v = scrollView.subviews[0]
        
        for (i, btn) in v.subviews.enumerated() {
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim.fromValue = btn.center.y + 400
            anim.toValue = btn.center.y
            
            anim.springBounciness = 8
            anim.springSpeed = 8
            
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i)*0.025
            
            btn.layer.pop_add(anim, forKey: nil)
        }
    }
}

extension WBComposeTypeView {
    func setupUI(){
        layoutIfNeeded()
        
        let rect = scrollView.bounds
        let width = scrollView.bounds.width
        for i in 0..<2{
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i)*width, dy: 0))
            addButtons(v: v, idx: i*6)
            scrollView.addSubview(v)
        }
        scrollView.contentSize = CGSize(width: CGFloat(2)*width, height: 0)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.isScrollEnabled = false
    }
    func addButtons(v: UIView, idx: Int){
        let count = 6
        for i in idx..<(idx + count){
            if i >= buttonsInfo.count {
                break
            }
            let dict = buttonsInfo[i]
            guard let imageName = dict["imageName"],let title = dict["title"] else
            {
                continue
            }
            let btn = WBComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            v.addSubview(btn)
            
            if let actionName = dict["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            else{
                // FIXME: -
                btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
            }
            btn.clsName = dict["clsName"]
        }
        let btnSize = CGSize(width: 100, height: 100)
        let margin = (v.bounds.width - 3*btnSize.width) / 4
        for (i, btn) in v.subviews.enumerated(){
            let y:CGFloat = (i > 2) ? v.bounds.height - btnSize.height : 0
            let col = i % 3
            let x = CGFloat(col + 1) * margin + CGFloat(col) * btnSize.width
            btn.frame = CGRect(x: x, y: y, width: btnSize.width, height: btnSize.height)
            print(String.init(format: "x: %f, y:%f, i:%f, col:%f", x, y, i, col))
        }
    }
}
